package cn.myfirefly.core.mybatis;

import java.util.HashMap;
import java.util.Map;

import cn.myfirefly.core.model.BaseFilterDto;
import cn.myfirefly.utils.FilterUtil;
import cn.myfirefly.utils.StrUtil;

public class BjuiDataGridSqlHelper {
	protected static final ThreadLocal<BjuiDataGridFilter> LOCAL_FILTER = new ThreadLocal<BjuiDataGridFilter>();
	
	public static BjuiDataGridFilter addFilter(BaseFilterDto dto) {
		return addFilter(dto, null);
	}
	
	public static BjuiDataGridFilter addFilter(BaseFilterDto dto, String tableName) {
		BjuiDataGridFilter filter = getFilter();
		if (filter == null) {
			filter = new BjuiDataGridFilter(dto);
		}
		if (StrUtil.isBlank(tableName)) {
			tableName = filter.getTableName();
		}
		StringBuffer querySql = new StringBuffer();
		Map<String, Object> param = new HashMap<>();
		FilterUtil.handleFilterSql(dto, tableName, querySql, param);
		filter.setFilterSql(querySql.toString());
		filter.setParam(param);
		setFilter(filter);
		return filter;
	}
	
	public static BjuiDataGridFilter getFilter() {
		return LOCAL_FILTER.get();
	}
	
	public static void setFilter(BjuiDataGridFilter filter) {
		LOCAL_FILTER.set(filter);
	}
	
	public static void clearFilter() {
		LOCAL_FILTER.remove();
	}
}
